﻿app.directive("repeatFinish", function () {
    return function (scope, element, attrs) {
        if (scope.$last) setTimeout(function () {
            scope.$emit("repeatFinish", element, attrs);
        }, 1);
    };
});

app.controller("ngGraphListController", function ($scope, $http, $location) {
    $scope.sets = [];
    var bundler = new MrGraphieBundler();
    var GetGraph = new GraphTemplates();
    var MrGraphie = new CanvasGraph();

    $scope.$on("repeatFinish", function (scope, element, attrs) {
        renderGraphThumbnails();
    });

    $scope.getSetList = function () {
        $http.get("/api/set/").success(function (data) {
            //$scope.sets = data;

            for (var i in data) {
                var s = [];
                for (var j in data[i].graphs) {
                    var t = bundler.unbundle(data[i].graphs[j], GetGraph);
                    s.push(t);
                }
                var set = {
                    id: data[i].id,
                    xMin: data[i].xMin,
                    xMax: data[i].xMax,
                    yMin: data[i].yMin,
                    yMax: data[i].yMax,
                    graphs: s
                };
                $scope.sets.push(set);
            }
        }).error(function (data) {
            console.log(data);
        })
    };

    var renderGraphThumbnails = function () {
        for (var s in $scope.sets) {
            var canvasInfo = {
                xMin: $scope.sets[s].xMin,
                xMax: $scope.sets[s].xMax,
                yMin: $scope.sets[s].yMin,
                yMax: $scope.sets[s].yMax,
                //canvasColor: "black",
                //guideColor: "gray",
                //axisColor: "white",
                backgroundStyle: "grid",
                guideWidth: 0.3,
                axisWidth: 0.3
            };
            for (var g in $scope.sets[s].graphs) {
                MrGraphie.render("canvas-" + $scope.sets[s].id, canvasInfo, $scope.sets[s].graphs[g]);
            }

        }
    };

    $scope.deleteSet = function (index) {
        var id = $scope.sets[index].id
        $http.delete("/api/set/" + id).success(function () {
            $scope.sets.splice(index, 1);
        }).error(function (data) {
            console.log(data);
        });
    };

    $scope.viewSet = function (id) {
        $location.path("/set/" + id);
    };

    $scope.getSetList();
});